<template>
	<div class="root rounded-lg mb-2 p-1">
		<div v-for="nft in nftList" :key="nft.id" class="token-display">
		
			<p><span>NFT Name:</span> {{ nft.nft_name }}</p>
			<p><span>img:</span> {{ nft.nft_img}}</p>
			<p><span>Nft Symbol:</span> {{ nft.nft_symbol}}</p>
	
			<!-- 添加按钮 -->
            <button @click="deposit(nft.nft_id)">Stake NFT</button>
		
		</div>
	</div>
</template>


<script setup>
    import {
        ref,
        onMounted
    } from 'vue';
    
    import {
        PublicKey,
        Connection,
		LAMPORTS_PER_SOL,
        SYSVAR_RENT_PUBKEY,
        SystemProgram
    } from "@solana/web3.js";
    import { AnchorError } from '@coral-xyz/anchor';
  
    import {
        Metaplex,
        keypairIdentity,
        bundlrStorage,
        Metadata
    } from "@metaplex-foundation/js";
    import bs58 from 'bs58';
    import {
        BN
    } from "bn.js";
    import {
        useRouter
    } from 'vue-router';
    import {
        ASSOCIATED_PROGRAM_ID,
        TOKEN_PROGRAM_ID,
        associatedAddress
    } from "@coral-xyz/anchor/dist/cjs/utils/token";
    import {
        ENV,
        TokenListProvider
    } from "@solana/spl-token-registry";
    import * as anchor from "@coral-xyz/anchor";
	import store from '../vuex';
    
    // 定义响应式变量来存储代币数据
    const nftList = ref([]);
  

    // 定义 loadData 函数
    async function getNft() {
    
		const workspaceValue = store.state.workspace.value;
        if (!workspaceValue) {
            console.error('Workspace is not initialized.');
            return;
        }
        
        const {
            connection,
            program,
            wallet,
            provider
        } = workspaceValue;

        let img = '';
      
        try {
            const ownerstring = provider.wallet.publicKey.toBase58();
            const ownerkey = provider.wallet.publicKey;
            const url = `https://devnet.helius-rpc.com/?api-key=78483ff4-5689-45fe-a8da-f569c3894e07`;

            const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
            jsonrpc: '2.0',
            id: 'my-id',
            method: 'searchAssets',
            params: {
                    ownerAddress: ownerstring,
                    grouping: ["collection", "6SqihPjBVhUEZaYUHZRDixK8DKXzLUovRyZYrTgSsvWj"],
                    page: 1,
                    limit: 1000
            },
                }),
            });
                    
        const { result } = await response.json();
        //console.log(result);

        let filteredResults = [];

        result.items.forEach(nft => {
                  
                    
            const nft_img = nft.content.links.image;
                    
            const nft_id = nft.id;
                    
            const nft_name = nft.content.metadata.name;
                    
            const nft_symbol= nft.content.metadata.symbol;
                    
            
            filteredResults.push({
                nft_id:nft_id,
                nft_name: nft_name,
                nft_symbol:nft_symbol,
                nft_img:nft_img
            });
               
            
        });
            
        console.log(filteredResults);
        nftList.value = filteredResults;

        } catch (error) {
            console.error('Failed to load data:', error);
        }
    }

    onMounted(() => {
        store.commit('initWorkspace', {
            callback: () => {
                getNft(); 
            }
        });
    });


    async function deposit(nftId){

        store.commit('initWorkspace', {
        callback: () => {
            stake(nftId);
        }
        });

  
    }

    async function stake(nftId) {
        const METADATA_PROGRAM = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
        const workspaceValue = store.state.workspace.value;
        if (!workspaceValue) {
        console.error('Workspace is not initialized.');
        return;
        }
        const { wallet, connection, provider, program } = workspaceValue;

        //组装数据
        let timestamp = Math.floor(new Date().getTime() / 1000);
        const owner = provider.wallet.publicKey;
  
        let nft_mint = new PublicKey(nftId);//预售得到的nft mint地址
        const user_token_account =  associatedAddress({
        mint: nft_mint,
        owner: owner
        });
        const plat_token_account = PublicKey.findProgramAddressSync([Buffer.from("plat_token"), nft_mint.toBuffer()], program.programId)[0];
        const saleinfo = anchor.web3.PublicKey.findProgramAddressSync([new BN(timestamp).toArrayLike(Buffer, "le", 8)], program.programId)[0];
        let pledge_pool = PublicKey.findProgramAddressSync([Buffer.from("pledge_pool")], program.programId)[0];
        let pledge_user = PublicKey.findProgramAddressSync([owner.toBuffer()], program.programId)[0];


       



        const modifyComputeUnits = anchor.web3.ComputeBudgetProgram.setComputeUnitLimit({
            units: 500_000,
        });

        

        try {

            const tx = await program.methods
                .pledgeNft(new BN(timestamp))
                .accounts({
                    user: owner,
                    nftMint: nft_mint,
                    userTokenAccount: user_token_account,
                    platTokenAccount: plat_token_account,
                    saleinfo: saleinfo,
                    pledgePool: pledge_pool,
                    pledgeUser: pledge_user,
                    systemProgram: SystemProgram.programId,
                    tokenProgram: TOKEN_PROGRAM_ID,
                    associatedTokenProgram: ASSOCIATED_PROGRAM_ID,
                    rent: SYSVAR_RENT_PUBKEY,
                })
                .signers([])
                .rpc();

        console.log("Your transaction signature", tx);


        } catch (error) {
            
            if (error instanceof AnchorError) {
                
                
                const code = error.error.errorCode.code ;
                const number = error.error.errorCode.number ;
                const  message = error.error.errorMessage;
                
                console.error('捕获到的错误: ', code,number,message);
                // 在这里处理错误，例如显示错误消息给用户
            } else {
                // 处理其他类型的错误
                console.error('未知错误: ', error);
            }
            }

}


    //用户
    function formatDate(date) {
        date = new Date(parseInt(date));
        return new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        }).format(date);
    }



  


</script>
<style scoped>
	/* 设置组件的根元素背景颜色和文本颜色 */
	.root {
		background-color: #f0f0f0 !important;
		/* 浅灰色背景 */
		color: #333 !important;
		/* 深灰色文本 */
		overflow: auto;
		width: 80%;
		max-width: 600px;
		height: 80%;
	}

	/* 设置 token 显示区域的样式 */
	.token-display {
		background-color: #fff !important;
		/* 白色背景 */
		border: 1px solid #ddd !important;
		/* 边框颜色 */
		padding: 16px !important;
		/* 内边距 */
		margin: 8px 0 !important;
		/* 外边距 */
		border-radius: 8px !important;
		/* 圆角边框 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
		word-break: break-all;
		/* 添加阴影效果 */
	}

	/* 为了提高可读性，您可以为文本添加一些间距 */
	p {
		line-height: 1.6 !important;
		/* 行高 */
		margin-bottom: 16px !important;
		/* 段落之间的间距 */
	}
	span{
		font-weight: bold;
		color: #444444;
	}
</style>